package com.xzh.wms.service;

import cn.hutool.core.util.ObjectUtil;
import cn.xzh.smart.core.exception.BizException;
import com.xzh.wms.dao.InventoryBatchDao;
import com.xzh.wms.dao.InventoryDao;
import com.xzh.wms.dao.OdoItemDao;
import com.xzh.wms.dto.InventoryOptionDTO;
import com.xzh.wms.entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("saleOut")
public class SaleOutInventoryOptionServiceImpl implements IInventoryOptionService{

    @Autowired
    private OdoItemDao odoItemDao;
    @Autowired
    private InventoryDao inventoryDao;
    @Autowired
    private InventoryBatchDao inventoryBatchDao;
    @Override
    public void process(InventoryOptionDTO dto) {
        String id = dto.getRefId();
        OdoItemQuery query = new OdoItemQuery().builder().odoId(id).build();
        List<OdoItem> odoItems = odoItemDao.select(query);
        odoItems.forEach(item->{
            InventoryQuery query1 = new InventoryQuery().builder().id(item.getProductId()).build();
            List<Inventory> inventories = inventoryDao.select(query1);
            if (ObjectUtil.isEmpty(inventories)){
               throw new BizException(456, "库存不存在");
            }else {
                Inventory inventory = inventories.get(0);
                if (item.getOutQty()>inventory.getQty()){
                    throw new BizException(455, "库存不足");
                }
                Integer i = inventoryDao.updateOutQty(item.getOutQty(), item.getProductId(), inventory.getVersion());
                if (i==0){
                    throw new BizException(454, "库存更新失败");
                }
            }
            String batchId = item.getBatchId();
            InventoryBatchQuery query2 = new InventoryBatchQuery().builder().batchId(batchId).build();
            List<InventoryBatch> inventoryBatches = inventoryBatchDao.select(query2);
            if (ObjectUtil.isEmpty(inventoryBatches)){
                throw new BizException(457, "批次不存在");
            }else {
                InventoryBatch inventoryBatch = inventoryBatches.get(0);
                if (item.getOutQty()>inventoryBatch.getQty()){
                    throw new BizException(458, "库存不足");
                }
                Integer i = inventoryBatchDao.updateOutQty(item.getOutQty(), batchId, inventoryBatch.getVersion());
            }
        });
    }
}
